package Cn.Sarkar

import Cn.Sarkar.EntityDream.CoreEngine.RDBMS.Core.PipeLine.CorePipeLine
import Cn.Sarkar.EntityDream.CoreEngine.RDBMS.Core.PipeLine.IPipeLineSubject
import Cn.Sarkar.EntityDream.CoreEngine.RDBMS.Core.PipeLine.Subjects.GenerateInsertTaskSubject
import Cn.Sarkar.EntityDream.CoreEngine.RDBMS.Core.PipeLine.Subjects.SaveChangesEventState
import Cn.Sarkar.EntityDream.CoreEngine.RDBMS.Core.PipeLine.Subjects.SaveChangesEventSubject
import Cn.Sarkar.EntityDream.CoreEngine.RDBMS.Core.PipeLine.Subjects.TranslationSubject
import Cn.Sarkar.EntityDream.CoreEngine.RDBMS.IDataContext
import Cn.Sarkar.EntityDream.Pipeline.Core.Info.FeatureInfo
import Cn.Sarkar.EntityDream.Pipeline.Core.PipeLineContext
import Cn.Sarkar.EntityDream.Pipeline.Core.PipeLineFeature
import Cn.Sarkar.EntityDream.Pipeline.Core.PipeLineFeatureMetaData
import Cn.Sarkar.Entities.Common.BaseEntity
import org.joda.time.DateTime
import java.util.*

class logger : PipeLineFeature<IPipeLineSubject, IDataContext>() {
    override val getMetaData: PipeLineFeatureMetaData by lazy {
        PipeLineFeatureMetaData(CorePipeLine.afterProcess, "SarkarMMS.DB.Logger")
    }
    override val info: FeatureInfo by lazy {
        FeatureInfo(
                "Logger",
                "Sarkar Software Technologys SarkarMMS internal logger",
                "Sarkar Software Technologys",
                "yeganaaa",
                1,
                "v0.1"
        )
    }

    override fun PipeLineContext<IPipeLineSubject, IDataContext>.onExecute(subject: IPipeLineSubject) {
        if (subject is TranslationSubject) {
            println("SQL::==> ${subject.translationResult!!.fullSqlQuery}")
        }
    }
}

class DataVersionManager : PipeLineFeature<IPipeLineSubject, IDataContext>() {
    override val getMetaData: PipeLineFeatureMetaData by lazy { PipeLineFeatureMetaData(CorePipeLine.beforeProcess, "DataVersionManager") }
    override val info: FeatureInfo by lazy { FeatureInfo("DataVersionManager", "DataVersionManager", "Sarkar Software Technologys", "yeganaaa", 1, "v0.1") }

    override fun PipeLineContext<IPipeLineSubject, IDataContext>.onExecute(subject: IPipeLineSubject) {
        if (subject is GenerateInsertTaskSubject) {
            val entity = subject.entity
            if (entity is BaseEntity) {
                entity.guid = UUID.randomUUID().toString().replace("-", "").toUpperCase()
                entity.createdTime = DateTime.now()
                entity.lastUpdatedTime = DateTime.now()
                entity.dataVersion = 1
            }
        }
        if (subject is SaveChangesEventSubject && subject.State == SaveChangesEventState.Begin) {
            featureContext.updateTasks.forEach {
                val entity = it.value.entity
                if (entity is BaseEntity) {
                    entity.lastUpdatedTime = DateTime.now()
                    entity.dataVersion++
                }
            }
        }
    }
}